package com.erikpasternak.vader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;


public class SettingsFragment extends Fragment implements View.OnClickListener {
    private static final String TAG = "SettingsFrag";
    private static final boolean DEBUG = false;

	private VaderActivity.VaderStateListener mListener;
    private final EditText[] mIngredients = new EditText[SharedPrefsHelper.MAX_INGREDIENTS];
    private final EditText[] mCosts = new EditText[SharedPrefsHelper.MAX_INGREDIENTS];
    private SharedPrefsHelper mHelper;
    private DrinkDbHelper mDbHelper;
    private AdkHelper mAdkHelper;
    private EditText mMaxUnits;
    private CheckBox mUseVideo;
    private Button mCleanButton;
    private Button mResetButton;
    private EditText mEmptyId;
    private Button mEmptyButton;

    private boolean mWaitingForAdk = false;

    private AdkHelper.Listener mAdkListener = new AdkHelper.Listener() {

        public void onSendFailed(int command) {
            Toast.makeText(getActivity(), "Message failed", Toast.LENGTH_SHORT).show();
            mWaitingForAdk = false;
            setButtonsEnabled(true);
        }

        public void onMessageReceived(int command, int length, byte[] data) {
            if (DEBUG) {
                Toast.makeText(getActivity(), "Received command " + command, Toast.LENGTH_SHORT)
                        .show();
            }
            if (command == AdkHelper.ADK_COMMAND_INGREDIENT_DONE) {
                mWaitingForAdk = false;
                setButtonsEnabled(true);
            }
        }
    };

    public SettingsFragment() {
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
        VaderActivity va = (VaderActivity) activity;
        mListener = va.getListener();
        mDbHelper = va.getDbHelper();
        mAdkHelper = va.getAdkHelper();
        mHelper = new SharedPrefsHelper(activity);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle bundle) {
        View view = inflater.inflate(R.layout.settings, parent, false);
		view.findViewById(R.id.next).setOnClickListener(this);
        view.findViewById(R.id.update).setOnClickListener(this);
        mMaxUnits = (EditText) view.findViewById(R.id.max_units);
        mUseVideo = (CheckBox) view.findViewById(R.id.use_video);
        mCleanButton = (Button) view.findViewById(R.id.clean_button);
        mResetButton = (Button) view.findViewById(R.id.reset_button);
        mEmptyId = (EditText) view.findViewById(R.id.empty_id);
        mEmptyButton = (Button) view.findViewById(R.id.empty_button);

        mCleanButton.setOnClickListener(this);
        mResetButton.setOnClickListener(this);
        mEmptyButton.setOnClickListener(this);

        mMaxUnits.setText(Integer.toString(mHelper.getMaxUnits()));
        mUseVideo.setChecked(mHelper.getRequireVideo());

        mIngredients[0] = (EditText) view.findViewById(R.id.i1);
        mIngredients[1] = (EditText) view.findViewById(R.id.i2);
        mIngredients[2] = (EditText) view.findViewById(R.id.i3);
        mIngredients[3] = (EditText) view.findViewById(R.id.i4);
        mIngredients[4] = (EditText) view.findViewById(R.id.i5);
        mIngredients[5] = (EditText) view.findViewById(R.id.i6);
        mIngredients[6] = (EditText) view.findViewById(R.id.i7);
        mIngredients[7] = (EditText) view.findViewById(R.id.i8);
        mCosts[0] = (EditText) view.findViewById(R.id.c1);
        mCosts[1] = (EditText) view.findViewById(R.id.c2);
        mCosts[2] = (EditText) view.findViewById(R.id.c3);
        mCosts[3] = (EditText) view.findViewById(R.id.c4);
        mCosts[4] = (EditText) view.findViewById(R.id.c5);
        mCosts[5] = (EditText) view.findViewById(R.id.c6);
        mCosts[6] = (EditText) view.findViewById(R.id.c7);
        mCosts[7] = (EditText) view.findViewById(R.id.c8);

		return view;
	}

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "ON RESUME*****");
        if (DEBUG) {
            Toast.makeText(getActivity(), "SETTINGS RESUMING", Toast.LENGTH_SHORT).show();
        }
        String[] ingredients = mHelper.getIngredients();
        for (int i = 0; i < ingredients.length; i += 2) {
            mIngredients[i / 2].setText(ingredients[i]);
            mCosts[i / 2].setText(ingredients[i + 1]);
        }
        if (DEBUG) {
            Toast.makeText(getActivity(), "AdkHelper is " + mAdkHelper, Toast.LENGTH_SHORT).show();
        }
        if (mAdkHelper != null) {
            mAdkHelper.addListener(mAdkListener);
        }
    }

    @Override
    public void onPause() {
        if (mAdkHelper != null) {
            mAdkHelper.removeListener(mAdkListener);
        }
        super.onPause();
    }

    private void setButtonsEnabled(boolean enabled) {
        mCleanButton.setEnabled(enabled);
        mResetButton.setEnabled(enabled);
        mEmptyButton.setEnabled(enabled);
    }

	public void onClick(View v) {
        Log.d(TAG, "View clicked with id " + v.getId() + " clean=" + R.id.clean_button);
        if (v.getId() == R.id.empty_button) {

            int maxUnits = 24;
            try {
                maxUnits = Integer.parseInt(mMaxUnits.getText().toString());
            } catch (NumberFormatException e) {
                // ignore
            }
            String emptyId = mEmptyId.getText().toString();
            if (!TextUtils.isEmpty(emptyId)) {
                try {
                    int id = Integer.parseInt(emptyId);
                    mAdkHelper.sendCommand(AdkHelper.COMMAND_MIX, (byte) 2, new byte[] {
                            (byte) id, (byte) maxUnits
                    });
                    setButtonsEnabled(false);
                } catch (NumberFormatException e) {
                    Log.d(TAG, "That's not a number! " + emptyId);
                }
            }
        } else if (v.getId() == R.id.clean_button) {
            mAdkHelper.sendCommand(AdkHelper.COMMAND_MIX, (byte) AdkHelper.CLEAN_MSG_VALUES.length,
                    AdkHelper.CLEAN_MSG_VALUES);
            mWaitingForAdk = true;
            setButtonsEnabled(false);
        } else if (v.getId() == R.id.reset_button) {
            mAdkHelper.sendCommand(AdkHelper.COMMAND_MIX, (byte) AdkHelper.RETURN_MSG_VALUES.length,
                    AdkHelper.RETURN_MSG_VALUES);
            mWaitingForAdk = true;
            setButtonsEnabled(false);
        } else if (v.getId() == R.id.update) {
            InputStream is;
            try {
                is = new FileInputStream(new File(Environment.getExternalStorageDirectory(),
                        "drinks.txt"));
            } catch (FileNotFoundException e) {
                Log.d(TAG, "Horrible news! No drinks file!");
                return;
            }
            DrinkDbHelper.populateDb(mDbHelper.getWritableDatabase(), is);
        } else {
            String[] ingredients = new String[SharedPrefsHelper.MAX_INGREDIENTS];
            float[] costs = new float[SharedPrefsHelper.MAX_INGREDIENTS];
            for (int i = 0; i < mIngredients.length; i++) {
                String ingredient = mIngredients[i].getText().toString().toLowerCase().trim();
                ingredients[i] = ingredient;
                String cost = mCosts[i].getText().toString().trim();
                costs[i] = 0;
                if (!TextUtils.isEmpty(cost)) {
                    try {
                        costs[i] = Float.parseFloat(cost);
                    } catch (NumberFormatException e) {
                        Toast.makeText(getActivity(), "Price for " + ingredient
                                + " isn't a valid number", Toast.LENGTH_SHORT);
                    }
                }
            }
            int maxUnits = 24;
            try {
                maxUnits = Integer.parseInt(mMaxUnits.getText().toString());
            } catch (NumberFormatException e) {
                // ignore
            }
            mHelper.setIngredients(ingredients, costs);
            mHelper.setMaxUnits(maxUnits);
            mHelper.setRequireVideo(mUseVideo.isChecked());
            mListener.onStateChange(VaderActivity.STATE_INITIAL);
        }
	}
}
